package com.zy.dao.redis;

import java.io.Serializable;
import java.util.Set;
import java.util.concurrent.TimeUnit;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.data.redis.core.RedisTemplate;

import com.alibaba.fastjson.JSONObject;
import com.zy.pojo.vos.common.MsgVo;

public final class RedisRepository {

	private static final Logger LOG = LogManager.getLogger(RedisRepository.class);

	private RedisTemplate<Serializable, Object> redisTemplate;

	private long defaultExpireTime = 3600L;

	public void clear(final Serializable pattern) {
		Set<Serializable> keys = this.keys(pattern);
		for (Serializable key : keys)
			this.delete(key);
	}

	public void delete(final Serializable key) {
		if (exist(key))
			this.redisTemplate.delete(key);
	}

	public void delete(final Serializable... keys) {
		for (Serializable key : keys)
			this.delete(key);
	}

	public boolean exist(final Serializable key) {
		return this.redisTemplate.hasKey(key);
	}

	public Object get(final Serializable key) {
		return this.redisTemplate.opsForValue().get(key);
	}

	public Set<Serializable> keys(final Serializable pattern) {
		return this.redisTemplate.keys(pattern);
	}

	public boolean set(final Serializable key, final Object value, Long expireTime) {
		boolean result = false;
		try {
			redisTemplate.opsForValue().set(key, value);
			if (expireTime == null)
				redisTemplate.expire(key, this.defaultExpireTime, TimeUnit.SECONDS);
			else
				redisTemplate.expire(key, expireTime, TimeUnit.SECONDS);
			result = true;
		} catch (Exception e) {
			LOG.error(e.getMessage(), e);
		}
		return result;
	}

	public void saveMsg(MsgVo vo, Long minutes) {
		this.redisTemplate.expire(JSONObject.toJSONString(vo), minutes, TimeUnit.MINUTES);
	}

	public void setRedisTemplate(RedisTemplate<Serializable, Object> redisTemplate) {
		this.redisTemplate = redisTemplate;
	}

	public Long getDefaultExpireTime() {
		return defaultExpireTime;
	}

	public void setDefaultExpireTime(Long defaultExpireTime) {
		this.defaultExpireTime = defaultExpireTime;
	}

}
